package lc20240528;

import lc20240526.ListNode;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description: 反转left-right之间链表
 * @date 2024/5/28 21:10
 */
public class ReverseList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));

        ListNode newHead = reverseBetween(head, 2, 4);
        while (newHead != null) {
            System.out.print(newHead.val + " ");
            newHead = newHead.next;
        }
    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {

        if (head == null || right == left) {
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        //避免出现left等于1的情况。

        //找到第一个节点,i从1开始
        for (int i = 1; i < left; i++) {
            prev = prev.next;
        }

        ListNode start = prev.next;
        ListNode then = start.next;

        for (int i = 0; i < right - left; i++) {
            start.next = then.next;
            then.next = prev.next;
            prev.next = then;
            then = start.next;
        }
        return dummy.next;
    }
}
